/*
 * Project Name spring-boot-tools
 * File Name FieldInfo
 * Package Name com.huxiaosu.toole.autocreate.utils
 * Create Time 2024/7/11
 * Create by name：liujie
 */
package com.huxiaosu.tools.autocreate.utils;

import lombok.Data;

import java.sql.JDBCType;
import java.util.Arrays;

/**
 * Description
 *
 * @author liujie
 * @date 2024/7/11 15:28
 */
@Data
public class FieldInfo {
    /**
     * 字段名字
     */
    private String column;

    /**
     * MySQL 字段类型
     */
    private String jdbcType;

    /**
     * 字段描述
     */
    private String comment;

    /**
     * 长度
     */
    private int length;

    /**
     * 是否允许为空；默认允许
     */
    private boolean isNull = true;

    /**
     * 是否为主键；默认不是
     */
    private boolean isKey = false;

    /** 主键是不是自增 */
    private boolean isAutoIncrement = false;

    private boolean needLength = false;
    public void setJdbcType(String jdbcType) {
        this.jdbcType = jdbcType;
        this.setNeedLength(false);
    }

    public void setKey(boolean key) {
        isKey = key;
        this.setNeedLength(false);
    }

    public void setNeedLength(boolean needLength) {
        if (this.isKey) {
            this.needLength = true;
            this.length = 11;
            return;
        }
        if (this.jdbcType.equalsIgnoreCase(JDBCType.VARCHAR.getName())) {
            this.length = 200;
            this.needLength = true;
        } if(checkSetNeedLength()){
            // if trur 添加长度
            this.length = 200;
            this.needLength = true;
        }else {
            this.needLength = needLength;
        }
    }

    final static String[] NOT_REQUIRED = {
            JDBCType.DATE.getName(),JDBCType.TIMESTAMP.getName(),JDBCType.DATE.getName(),JDBCType.BLOB.getName()
            ,JDBCType.CLOB.getName()
    };
    private boolean checkSetNeedLength(){
        return Arrays.stream(NOT_REQUIRED).noneMatch(item -> item.equalsIgnoreCase(this.jdbcType));
    }

}